// 一些辅助用的工具方法
// 很多都是gross hack, 属于历史遗留问题

// antd从2.x开始引入了moment: http://momentjs.com/docs/
// 这是个好东西, 处理日期方便多了, 简直就是javascript界的joda-time
// 这些prototype的hack基本用不到了
// 不过它format时的pattern和常见的不太一样, 比如要大写的YYYY才代表年份
import moment from 'moment';
import districtData from './district.json';

/** 对Date的扩展，将 Date 转化为指定格式的String * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q)
 * 可以用 1-2 个占位符 * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
 * eg:
 * (new Date()).pattern("yyyy-MM-dd hh:mm:ss.S")==> 2006-07-02 08:09:04.423
 * (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04
 * (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04
 * (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04
 * (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
 */

export function fixedZero(val) {
  return val * 1 < 10 ? `0${val}` : val;
}

Date.prototype.format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时
    "H+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  };
  var week = {
    "0": "/u65e5",
    "1": "/u4e00",
    "2": "/u4e8c",
    "3": "/u4e09",
    "4": "/u56db",
    "5": "/u4e94",
    "6": "/u516d"
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  if (/(E+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[this.getDay() + ""]);
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }
  return fmt;
};

/**
 * 在当前日期的基础上再增加几天
 *
 * @param num 要增加的天数
 */
Date.prototype.plusDays = function (num) {
  var tmp = new Date();
  tmp.setDate(this.getDate() + num);
  return tmp;
};

// 为了克服js的一些坑...
const Utils = {
    isString(s) {
      return typeof (s) === 'string' || s instanceof String;
    },
    // 获取url中的所有参数
    getAllQueryParams() {
      let str = window.location.href;
      if (!str) {
        return {};
      }

      let num = str.indexOf('?');
      str = str.substr(num + 1); //取得所有参数

      const res = {};
      let name;
      let value;

      const arr = str.split('&'); //各个参数放到数组里
      for (let i = 0; i < arr.length; i++) {
        num = arr[i].indexOf('=');
        if (num > 0) {
          name = arr[i].substring(0, num).trim();
          value = arr[i].substr(num + 1).trim();
          res[name] = value;
        }
      }

      return res;
    },
    formatMoney(value, useUnit) {
      if (value !== +value) {
        return value;
      }

      let r = parseInt(value).toLocaleString() + value.toFixed(2).replace(/^-?\d+/, '');

      if (useUnit || useUnit === undefined) {
        return r + ' 元';
      } else {
        return r;
      }
    },
    map2kvArr(value,) {
      let a = [];

      for (let i in value) {
        a.push({
          key: i,
          value: value[i]
        });
      }

      return a;
    },

    /**
     * 通过属性值查找对象，存在则返回索引，不存在返回-1
     * @param arrayToSearch
     * @param attr
     * @param val
     * @returns {number}
     */
    findElem(arrayToSearch, attr, val) {
      for (let i = 0; i < arrayToSearch.length; i++) {
        if (arrayToSearch[i][attr] === val) {
          return i;
        }
      }
      return -1;
    },
    /**
     * 通过key对数组对象去重，返回新的数组
     * @param songs
     * @param key
     * @returns {Array}
     */
    uniqueByKey(songs, key) {

      let result = {};
      let finalResult = [];
      for (let i = 0; i < songs.length; i++) {
        result[songs[i][key]] = songs[i];
      }
      for (let item in result) {
        finalResult.push(result[item]);
      }

      return finalResult;
    },
    generateId(length) {
      return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36);
    },

    getTimeDistance(type) {
      const now = new Date();
      const oneDay = 1000 * 60 * 60 * 24;

      if (type === 'today') {
        now.setHours(0);
        now.setMinutes(0);
        now.setSeconds(0);
        return [moment(now), moment(now.getTime() + (oneDay - 1000))];
      }

      if (type === 'week') {
        let day = now.getDay();
        now.setHours(0);
        now.setMinutes(0);
        now.setSeconds(0);

        if (day === 0) {
          day = 6;
        } else {
          day -= 1;
        }

        const beginTime = now.getTime() - day * oneDay;

        return [moment(beginTime), moment(beginTime + (7 * oneDay - 1000))];
      }

      if (type === 'month') {
        const year = now.getFullYear();
        const month = now.getMonth();
        const nextDate = moment(now).add(1, 'months');
        const nextYear = nextDate.year();
        const nextMonth = nextDate.month();

        return [
          moment(`${year}-${fixedZero(month + 1)}-01 00:00:00`),
          moment(moment(`${nextYear}-${fixedZero(nextMonth + 1)}-01 00:00:00`).valueOf() - 1000),
        ];
      }

      if (type === 'year') {
        const year = now.getFullYear();

        return [moment(`${year}-01-01 00:00:00`), moment(`${year}-12-31 23:59:59`)];
      }
    },

    getOneMomentTime(mon) {
      const dt = new Date();
      const now = dt.format("yyyy-MM-dd") + " 23:59:59";
      dt.setMonth(dt.getMonth() - mon);
      const dtMonthAgo = dt.format("yyyy-MM-dd") + " 00:00:00";

      return [
        dtMonthAgo,
        now
      ];
    },

    getLatelyYear(Range) {
      const dt = new Date();
      const dateArr = [];
      for (let i = 0; i < Range; i++) {
        const time = dt.format("yyyy-MM");
        const date = {
          key: time,
          value: time,
        };
        dt.setMonth(dt.getMonth() - 1);
        dateArr.push(date);
      }
      return dateArr;
    },

    getDistrictData() {
      let antdDistrict =[];
      Object.keys(districtData).forEach((index) => {
        let itemLevel1 = {};
        let itemLevel2 = {};
        itemLevel1.value = districtData[index].code;
        itemLevel1.label = districtData[index].name;
        itemLevel1.children = [];
        let data = districtData[index].cities;
        Object.keys(data).forEach((index) => {
          itemLevel2.value = data[index].code;
          itemLevel2.label = data[index].name;
          itemLevel2.children = [];
          let data2 = data[index].districts;
          let itemLevel3 = {};
          itemLevel3.children = [];
          Object.keys(data2).forEach((index) => {
            itemLevel3.value = index;
            itemLevel3.label = data2[index];
            itemLevel2.children.push(itemLevel3);
            itemLevel3 = {};
          });
          itemLevel1.children.push(itemLevel2);
          itemLevel2 = {};
        });
        antdDistrict.push(itemLevel1)
      });

      return antdDistrict;
    }
  }
;


export default Utils;
